package com.application.Activity;

import java.util.ArrayList;

import ReadWriteXML.CMember;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.NotificationManager;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

import com.application.Controller.ActivityController;
import com.application.Controller.NetworkController;
import com.application.Controller.ReadWriteFileController;
import com.application.Network.Protocol;
import com.application.outdoor.InvoikeServices.OperationsInvoike;


public class frmBieuQuyetActivity extends Activity{
	public static String contentVote="";
	public static int timeVote;
	public static String userSender;
	public static Button btnagree ;
	public static Button btndisagree;
	int port = Protocol.PORT;
	private static int minutes;
	private int second;
	private Thread thread;
	private boolean isRunning;
	public static Runnable doEndTime;
	private AlertDialog.Builder _builder;
	private static int _minutes;
	private int _second;
	TextView txtTime;
	TextView txtTitle,txtTitleBieuQuyet;
	private Thread _bg;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.layout_bieu_quyet);
		
		/*Log.d("PEERDROID","time" +timeVote );
		minutes = timeVote / 60;
		second = timeVote - minutes * 60;
		runTimeVote();
		doEndTime=new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				doEndTime();
			}
		};*/
		_minutes = timeVote / 60;
		Log.d("Phu","begin phut="+_minutes);
		_second = timeVote - _minutes * 60;
		Log.d("Phu","begin giay="+_second);
		showTimeKick();
		NotificationManager mn=(NotificationManager)getSystemService(NOTIFICATION_SERVICE);
       
		
		Bundle ex = this.getIntent().getExtras();
		final int id = ex.getInt("ID");
		final int index = ex.getInt("INDEX");
		final String sender = ex.getString("SENDER");
		final String title = ex.getString("TITLE");
		Log.d("PEERDROID","Da nhan duoc address Sender: "+ sender);
		Log.d("PEERDROID","Da nhan duoc index: "+ index);
		mn.cancel(id);
		txtTitle=(TextView)findViewById(R.id.txtTitle);
		txtTitle.setText("Thời gian biểu quyết còn :");
		txtTime=(TextView)findViewById(R.id.txtTime);
		String s="Nội dung biểu quyết là về: \n"+contentVote;
		txtTitleBieuQuyet = (TextView)findViewById(R.id.txtTitleBieuQuyet);
		txtTitleBieuQuyet.setText(s);
		_builder=new AlertDialog.Builder(this);
		btnagree = (Button)findViewById(R.id.btnAgree);
		btnagree.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				int value = 1;
				if(NetworkController.isInDoor()){
					NetworkController.sendResultBieuQuyet(sender, index,value);
				}
				else if(NetworkController.isOutDoor()){
					try{
						Log.i("Phu", "nguoi gui="+CommonUtilities.nguoiDung.getTenDangNhap());
						Log.i("Phu", "nguoi nhan="+userSender);
						
						new OperationsInvoike().SendBieuQuyetFeedback(CommonUtilities.nguoiDung.getTenDangNhap(), userSender, value+"");
						
					}catch (Exception e) {
						Log.d("Phu", "Không thể gửi feedback biểu quyết");
					}
				}
				
				//ghi xuống file Log
				String text = "Thực hiện Biểu Quyết - Đồng ý..";
				checkIsThanhLapNhom(text);
				
				ArrayList<Activity> arrActivity=ActivityController.arrActivity;
				for(int i=0;i<arrActivity.size();i++){
					Activity ac=arrActivity.get(i);
					if(ac.getLocalClassName().equals("frmBieuQuyetActivity")){
						ActivityController.closeActivity(ac);
					}
				}
				finish();
				//frmBieuQuyetActivity.this.finish();
			}
		});
		
		btndisagree = (Button)findViewById(R.id.btnDisagree);
		btndisagree.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				int value = 0;
				if(NetworkController.isInDoor()){
					NetworkController.sendResultBieuQuyet(sender, index,value);
				}
				else if(NetworkController.isOutDoor()){
					try{
						
						new OperationsInvoike().SendBieuQuyetFeedback(CommonUtilities.nguoiDung.getTenDangNhap(), userSender, value+"");
						
					}catch (Exception e) {
						Log.d("Phu", "Không thể gửi feedback biểu quyết");
					}
				}
				
				//ghi xuống file Log
				String text = "Thực hiện Biểu Quyết - không Đồng ý..";
				checkIsThanhLapNhom(text);
				ArrayList<Activity> arrActivity=ActivityController.arrActivity;
				for(int i=0;i<arrActivity.size();i++){
					Activity ac=arrActivity.get(i);
					if(ac.getLocalClassName().equals("frmBieuQuyetActivity")){
						ActivityController.closeActivity(ac);
					}
				}
				finish();
				//frmBieuQuyetActivity.this.finish();
			}
		});
		
	}
	
	private void showTimeKick(){
		Log.d("Phu","vào show time");
		Log.d("Phu","show time phut= "+_minutes);
		Log.d("Phu","show time giay= "+_second);
		if(txtTime==null){
			txtTime=(TextView)findViewById(R.id.txtThoiGian);
			
		}
		String s="";
		if(_minutes<10){
			s+="0"+_minutes+":";
		}
		if(_second < 10){
			Log.d("Phu","giay <10");
			s+="0"+_second;
			//txtTime.setText(_minutes + ":0" + _second);
		}
		else{
			Log.d("Phu","giay >10");
			Log.d("Phu","min="+_minutes+" giay="+_second);
			s+=_second;
			//txtTime.setText(_minutes + ":" + _second);
			Log.d("Phu","");
		}
		txtTime.setText(s);
		isRunning = true;
		Log.d("Phu","is running");
		_bg =  new Thread(new Runnable() {
			

			@Override
			public void run() {
				try {
					Log.d("Phu","vào run");
					Log.d("Phu","time" +timeVote );
					Log.d("Phu","_time_min" + _minutes);
					Log.d("Phu","_time sec: " + _second);
					while(timeVote > 0 && isRunning) {
						if(_second == 0)
						{
							_second = 60;
							_minutes--;
						}
						Thread.sleep(1000);
						hander.sendMessage(hander.obtainMessage());
					}
					if(isRunning)
					{	//ActivityController.DoEndTime();
						Log.d("Phu","running");
						//NetworkController.doEndTimeKick();
						ActivityController.handler.post(new Runnable() {
							
							@Override
							public void run() {
								// TODO Auto-generated method stub
							doEndTime();	
							}
						});
						Log.d("Phu","Show do end time");
					}
				}
				catch (Throwable t) {
				}
			}
		});
		_bg.start();
		Log.d("Phu","sau start");
	}
	
	Handler hander=new Handler() {
		@Override
		public void handleMessage(Message msg) {
			Log.d("Phu","Vào hander");
			if(timeVote!=0){
				timeVote --;
				Log.d("Phu","time="+timeVote);
				_second--;
				String tgian="";
				if(_minutes<10){
					
					tgian+="0"+_minutes+":";
				}
				else{
					tgian+=_minutes+":";
				}
				if(_second < 10){
					tgian += "0" + _second;
				}
				else{
					tgian+=_second;
				}
				if(txtTime==null){
					txtTime=(TextView)findViewById(R.id.txtThoiGian);
					
				}
				txtTime.setText(tgian);
			}
			else{
				isRunning=false;
			}
		}
	};
	private void doEndTime()
	{
		Log.d("Phu","vào do end time");		
			_builder.setTitle("Thông báo")
			.setMessage("Đã hết thời gian biểu quyết")
			.setCancelable(false)
			.setPositiveButton("OK", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int id) {
					finish();					
				}
			});
			AlertDialog alert = _builder.create();
			alert.getWindow().setBackgroundDrawable(new ColorDrawable(Color.argb(0, 255, 255, 255))); 
			alert.show();
			//finish();
	}
	
	@Override
	public void onStop()
	{
		super.onStop();
		isRunning=false;
	//	_bg.stop();
	}
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		Log.d("PEERDROID","vao ondestroy");
		isRunning = false;
	//	_bg.stop();
	}
	
	@Override
	public void onStart()
	{
		super.onStart();
		ActivityController.setPeerActivity(this);
		ActivityController.addActivityToArray(this);
	//	getContext();
	}
	
	void closeWindow(){
		frmBieuQuyetActivity.this.finish();
	}
//	void getContext(){
//		myContext=this.getBaseContext();
//	}
	public void checkIsThanhLapNhom(String text){
		Log.d("Phu", "đã vào checkIsThanhLapNhom: " + text);
		if(NetworkController._peer.account.isThanhLapNhom != true){
			ArrayList<CMember> cmem = ReadWriteFileController.readMember(ReadWriteFileController.MEMBER_PATH);
	        for(int i=0; i<cmem.size(); i++){
	        	
	        	Log.d("Phu","Text: " +text);
	        	String name = NetworkController._peer.getAccount().get_Username();
	        	NetworkController.sendTextLog(cmem.get(i).get_ip(), text, name);
	        }
	        WriteToLogFile(text);
		}else{
			WriteToLogFile(text);
		}
	}
	
	public void WriteToLogFile(String text){
		
		Log.d("Phu","WriteToLogFile "+ NetworkController._peer.getAccount().get_Username() + "-"+ text );
        String username = NetworkController._peer.getAccount().get_Username();
        String tenNhom = NetworkController.getGroupName();
		Log.d("Phu", "ten nhom 2....: "+ tenNhom);
		String path = ReadWriteFileController.DIRECTORY + tenNhom+"LogList.xml";
		Log.d("Phu", "Path: "+ path);
        ReadWriteFileController.insertLogFile(path, text, username);
	}
	
	/*public void runTimeVote(){
		isRunning = true;
		thread = new Thread(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				try {
					Log.d("PEERDROID","da vao run thread");
					Log.d("PEERDROID","time" +timeVote );
					Log.d("PEERDROID","_time_min" + minutes);
					Log.d("PEERDROID","_time sec: " + second);
					while(timeVote > 0 && isRunning) {
						if(second == 0)
						{
							second = 60;
							minutes--;
						}
						Thread.sleep(1000);
						handler.sendMessage(handler.obtainMessage());
					}
					if(isRunning)
						//ActivityController.DoEndTime();
						Log.d("PEERDROID","running");
						NetworkController.doEndTimeKick();
						Log.d("PEERDROID","do end time");
				}
				catch (Throwable t) {
				}
			}
		}) ;
		thread.start();
	}*/
	
	/*Handler handler=new Handler() {
		@Override
		public void handleMessage(Message msg) {
			Log.d("PEERDROID","Vao hander");
			timeVote --;
			second--;
			
		}
	};*/
	
	/*private void doEndTime()
	{//vao do end time bi sai
		Log.d("PEERDROID","vao do end time");
		//set data current
		thread.stop();
		Log.d("PEERDROID","thread.stop();");
		_builder.setMessage("Đã hết thời gian biểu quyết!")
		.setCancelable(false)
		.setPositiveButton("OK", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int id) {
				finish();
			}
		});
		AlertDialog alert = _builder.create();
		alert.getWindow().setBackgroundDrawable(new ColorDrawable(Color.argb(0, 255, 255, 255))); 
		alert.show();
	}*/
}
